package com.training1.core.modules.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.training1.api.exception.ApiAuthenticationException;
import com.training1.api.login.APILoginUtil;
import com.training1.core.common.entity.UserEntity;
import com.training1.core.common.service.CrudService;
import com.training1.core.common.utils.DateUtils;
import com.training1.core.common.utils.IdGen;
import com.training1.core.common.utils.excel.ExcelUtil;
import com.training1.core.dto.APIRegisterDto;
import com.training1.core.entity.MemberEntity;
import com.training1.core.entity.MessageEntity;
import com.training1.core.modules.dao.MemberDao;
import com.training1.core.modules.dao.SystemSettingsDao;
import com.training1.core.modules.dao.UserDao;

@Service
@Transactional
public class MemberService extends CrudService<MemberDao,MemberEntity>{
	
	
	@Resource
	private MemberDao memberDao;
	
	@Resource
	private SystemSettingsDao systemSettingsDao;
	
	private static final Logger log = LoggerFactory.getLogger(MemberService.class);

	@Value("${api.debug}")
	private String debug;
	
	@Resource
	private SystemSettingsService systemSettings;
	
	@Override
	@Transactional(readOnly = false)
	public int save(MemberEntity entity) {
		if (entity.getId()==null){
			if(entity.getIsDefault() == 1){
				dao.updateAdd(entity);//将其他地址更新为非默认,需要做判断
			}
			 dao.insertAdd(entity);//插入地址
			 return dao.insert(entity);
		}else{
			if(entity.getIsDefault() == 1){
				dao.updateAdd( entity);//将其他地址更新为非默认,需要做判断
			}
			dao.updateAllAdd(entity);//改变地址
			return dao.update(entity);
		}
	}
	@Resource
	private UserDao userDao;
	
	@Resource
	@Value(value="${apiExpiration}")
	private String expiration;
	
	public List<UserEntity> findUserName(Map<String, Object> param){
		return userDao.findUserName(param);
	}
	
	public MemberEntity findMemberByRecommender(String param){
		return dao.findMemberByRecommender(param);
	}
	
	/**
	 * 获取黑名单flg
	 */
	public String findFlg(String cellphone,String oldPassword){
		return dao.findFlg(cellphone,oldPassword);
	}
	
	/**
	 * 更新会员密码,更新时间,更新人
	 */
	public void updateLoginPassword(String cellphone,String oldPassword,String newPassword){
		dao.updateLoginPassword(cellphone, oldPassword, newPassword);
	}
	
	/**
	 * 批量拉黑或者从黑名单移除
	 * @param 
	 * @return
	 */
	public void findMemberListById(Map<String, Object> param){
		memberDao.findMemberListById(param);
	}
	
	/**
	 * 弹框保存
	 * @param memberEntity
	 */
	public void updateAcc(MemberEntity memberEntity){
		memberDao.updateAcc(memberEntity);
	}
	/**
	 * 托管
	 * @param param
	 */
	public void updateMemberTrust(Map<String, Object> param){
		memberDao.updateMemberTrust(param);
	}
	
	/**
	 * 根据手机号更新
	 */
	public int updateByCell(MemberEntity entity){
		return dao.updateByCell(entity);
	}
	
	/**
	 * 弹框获取
	 * @param id
	 * @return
	 */
	public MemberEntity gett(Integer id){
		return dao.gett(id);
	}
	
	/**
	 * 根据token来取得用户
	 * @param loginToken
	 * @return
	 */
	public MemberEntity getMemberToken(String loginToken){
		Map<String, Object> param =  new HashMap<String, Object>();
		param.put("loginToken", loginToken);
		//过期时间设置，默认2小时
		long expiration = 2 * 60 * 60 * 1000;
		try{
			expiration = Long.valueOf(this.expiration) * 60 * 60 * 1000;
		}catch(Exception e){
			log.error("api过期时间设置错误：{}",e.getMessage());
		}
		MemberEntity member = dao.getToken(param);
		//判断token是否正确
		if(member==null){
			throw new ApiAuthenticationException(APILoginUtil.unAuthorityJsonString());
		}
		//判断是否超时
		// 待删除

		/*	Long tokenTime = member.getTokenTime();
			if(tokenTime==null){
				tokenTime = 0l;
			}
			if(System.currentTimeMillis()>(tokenTime + expiration)){
				//超时
				throw new ApiAuthenticationException(APILoginUtil.authorityTimeoutJsonString());
			}*/

//			Long tokenTime = member.getTokenTime();
//			if(tokenTime==null){
//				tokenTime = 0l;
//			}
//			if(System.currentTimeMillis()>(tokenTime + expiration)){
//				//超时
//				throw new ApiAuthenticationException(APILoginUtil.authorityTimeoutJsonString());
//			}
//git.oschina.net/zhangcd/training.git
		//判断黑名单
		if("1".equals(member.getBlackListFlag())){
			throw new ApiAuthenticationException(APILoginUtil.blanklistJsonString());
		}
		
		param.remove("loginToken");
		param.put("id", member.getId());
		param.put("tokenTime", System.currentTimeMillis());
		//更新登陆时间
		dao.updateToken(param);
		return member;
	}
	
	
	public String successLogin(MemberEntity member){
		return loginToToken(member.getId());
	}
	
	/**
	 * 更新token
	 * @param id
	 */
	private String loginToToken(Integer id){
		if(id==null){
			throw new ApiAuthenticationException("id不能为null");
		}
		String uuid = IdGen.uuid();
		Map<String, Object> param =  new HashMap<String, Object>();
		param.put("loginToken", uuid);
		param.put("id", id);
		param.put("tokenTime", System.currentTimeMillis());
		dao.updateToken(param);
		return uuid;
	}
	/**
	 * 登录验证 根据手机号找到用户
	 * @param cellPhone
	 * @return
	 */
	public MemberEntity findMember(String cellPhone){
		//账号密码判定
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cellPhone", cellPhone);
		MemberEntity member = dao.findMember(map);
		return member;
	}

	
	
	
	/**
	 * 更新密码
	 * @param cellPhone
	 * @param checkCode
	 */
	public void updatePassword(String cellPhone,String password){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cellPhone", cellPhone);
		map.put("password", password);
		dao.updatePassword(map);
	}
	
	/**
	 * 根据手机号获取会员名,推荐人手机号及姓名
	 * 能用的到
	 * @return
	 */
	public Map<String,String> getDetialByCell(String cellPhone){
		 Map<String,String> map = dao.getDetialByCell(cellPhone);
		return map;
	}
	
	/**
	 * 导出excel文件
	 * @param response
	 * @param param
	 */
	public void export(HttpServletResponse response,Map<String, Object> param) {
		List<MemberEntity> cqList = memberDao.findexportList(param);//根据dao中的内容用方法
		//设置列标题
		List<String> excelHead = new ArrayList<String>();
		excelHead.add("会员姓名");
		excelHead.add("会员手机");
		excelHead.add("开单中心");
		excelHead.add("性别");
		excelHead.add("身份证号码");
		excelHead.add("可提现额度");
		excelHead.add("会员状态");
		
		//设置内容
		List<List<String>> dataList = new ArrayList<List<String>>();
		for(MemberEntity cq : cqList){
			List<String> data = new ArrayList<String>();
			data.add(cq.getMemberName());
			data.add(cq.getCellPhone());
			data.add(cq.getUserName());
			if(cq.getGender() == 1){
				data.add("男");
			}
			else{
				data.add("女");
			}
			data.add(cq.getIdCardNumber());
			data.add(cq.getAvaibleCash().toString());
			if(cq.getBlackListFlag()==0){
				data.add("正常");
			}
			else{
				data.add("黑名单");
			}
		
			dataList.add(data);
		}
		
		//设置文件名
		String fileName;
		String sheetName = "sheet1";
		String titleName;
		fileName = "会员查询表_"+DateUtils.getDate().replace("-", "");
		titleName = "会员查询表_"+DateUtils.getDate().replace("-", "");
		
		ExcelUtil.exportExcel(response, excelHead, dataList, fileName, sheetName,titleName);
	}

	public MemberEntity getMember(String cellphone) {
		return dao.getMember(cellphone);
	}

	public List<MemberEntity> findBatch(List<String> list) {
		// TODO Auto-generated method stub
		return dao.findBatch(list);
	}

	public int updateBatch(List<MemberEntity> memList) {
		return dao.updateBatch(memList);
		
	}
	
	/**
	 *  根据手机号找到用户信息
	 * @param cellPhone
	 * @return
	 */
	public MemberEntity findMemberByPhone(String cellPhone){
		//账号密码判定
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cellPhone", cellPhone);
		MemberEntity member = memberDao.findMemberByPhone(map);
		return member;
	}
	public MemberEntity findCardCount(String cellPhone){
		//账号密码判定
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cellPhone", cellPhone);
		MemberEntity member = memberDao.findCardCount(map);
		return member;
	}
	//api的用户注册保存
	@Transactional(readOnly = false)
	public void register(APIRegisterDto registerDto){
		
		MessageEntity messageEntity = new MessageEntity();
		messageEntity.setMessageType(1);//1.用户注册 2.忘记密码
		messageEntity.setCellphone(registerDto.getCellphone());
		messageEntity.setCheckCode(registerDto.getIdentifying());
		
		MemberEntity memberEntity = new MemberEntity(); 
		memberEntity.setCellPhone(registerDto.getCellphone());
		memberEntity.setPassword(registerDto.getPassword());
		memberEntity.setBlackListFlag(0);//0.正常用户 1.黑名单用户
		memberEntity.setMemberType(2);//1：老用户 2：新用户
		
		memberDao.insertMessage(messageEntity);
		memberDao.insertMember(memberEntity);
	}

}
